<template>
  <nav class="h-20 bg-white shadow-sm fixed top-0 left-0 right-0 z-50 flex items-center justify-between px-8">
    <div class="flex items-center gap-8">
      <!-- EduLiveLink Logo -->
      <div class="flex items-center gap-4 bg-slate-800 px-5 py-3 rounded-lg">
        <div class="logo-icon w-12 h-12">
          <svg viewBox="0 0 100 100" fill="none">
            <circle cx="50" cy="50" r="45" stroke="url(#gradient1)" stroke-width="3" fill="none"/>
            <circle cx="50" cy="50" r="35" stroke="url(#gradient2)" stroke-width="2" fill="none"/>
            <path d="M30 40 L50 30 L70 40 L70 60 L50 70 L30 60 Z" fill="url(#gradient3)" opacity="0.8"/>
            <circle cx="50" cy="50" r="8" fill="white"/>
            <defs>
              <linearGradient id="gradient1" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color:#4A90E2"/>
                <stop offset="100%" style="stop-color:#7BB3F0"/>
              </linearGradient>
              <linearGradient id="gradient2" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color:#5BA0F2"/>
                <stop offset="100%" style="stop-color:#8CC8FF"/>
              </linearGradient>
              <linearGradient id="gradient3" x1="0%" y1="0%" x2="100%" y2="100%">
                <stop offset="0%" style="stop-color:#4A90E2"/>
                <stop offset="100%" style="stop-color:#6BB0FF"/>
              </linearGradient>
            </defs>
          </svg>
        </div>
        <div class="flex flex-col">
          <span class="text-xl font-bold text-blue-600">
            EduLiveLink
          </span>
          <span class="text-xs text-black">
            智能教育平台
          </span>
        </div>
      </div>
      
      <div class="flex gap-8">
        <router-link to="/" class="text-gray-600 hover:text-blue-600 transition-colors text-base font-medium">首页</router-link>
        <router-link to="/courses" class="text-gray-600 hover:text-blue-600 transition-colors text-base font-medium">课程商城</router-link>
        <router-link to="/student-classes" class="text-gray-600 hover:text-blue-600 transition-colors text-base font-medium">我的课程</router-link>
        <router-link to="/resources" class="text-gray-600 hover:text-blue-600 transition-colors text-base font-medium">资源</router-link>
      </div>
    </div>
    <div class="flex items-center gap-4">
      <el-input
        v-model="searchText"
        placeholder="搜索课程"
        class="w-48"
        :prefix-icon="Search"
        size="small"
      />
      <el-button type="primary" size="default" class="rounded px-6 font-medium" @click="startLearning">开始学习</el-button>
      <el-button type="info" size="default" class="rounded px-6 font-medium" @click="goToProfile">我的</el-button>
      
      <!-- 用户头像 -->
      <div class="flex items-center gap-3">
        <div class="w-10 h-10 rounded-full bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center cursor-pointer hover:shadow-lg transition-all duration-200 shadow-md" @click="goToProfile">
          <span class="text-white text-sm font-bold select-none">{{ getUserInitial() }}</span>
        </div>
        <div class="text-sm text-gray-600">
          <div class="font-medium">{{ userInfo.nickname || userInfo.name || '用户' }}</div>
          <div class="text-xs text-gray-400">{{ userInfo.username || userInfo.account || '加载中...' }}</div>
        </div>
      </div>
    </div>
  </nav>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import userApi from '../api/user.js'

const router = useRouter()
const searchText = ref('')

// 用户信息
const userInfo = reactive({
  nickname: '',
  name: '',
  username: '',
  account: '',
  realName: ''
})

// 获取用户信息
const loadUserInfo = async () => {
  try {
    // 首先尝试从sessionStorage获取
    const userInfoStr = sessionStorage.getItem('userInfo')
    if (userInfoStr) {
      const parsedUserInfo = JSON.parse(userInfoStr)
      // 检查用户信息是否完整（有用户名或账号）
      if (parsedUserInfo.name || parsedUserInfo.nickname || parsedUserInfo.account || parsedUserInfo.username) {
        Object.assign(userInfo, parsedUserInfo)
        console.log('✅ 从sessionStorage加载用户信息成功:', userInfo)
        return
      }
    }
    
    // 如果sessionStorage中没有完整的用户信息，尝试从API获取
    const userId = localStorage.getItem('userId')
    const token = localStorage.getItem('userToken')
    
    if (userId && token) {
      console.log('🔄 sessionStorage中用户信息不完整，从API重新获取...')
      try {
        const response = await userApi.getProfileById(userId)
        if (response && response.data) {
          const freshUserInfo = {
            name: response.data.name || response.data.nickname || '用户',
            nickname: response.data.nickname,
            username: response.data.username || response.data.account,
            account: response.data.account,
            realName: response.data.realName,
            role: response.data.role || 'user',
            ...response.data
          }
          
          // 更新响应式对象
          Object.assign(userInfo, freshUserInfo)
          
          // 保存到sessionStorage
          sessionStorage.setItem('userInfo', JSON.stringify(freshUserInfo))
          
          console.log('✅ 从API重新获取用户信息成功:', userInfo)
        }
      } catch (apiError) {
        console.warn('⚠️ 从API获取用户信息失败，使用默认值:', apiError)
        // 如果API调用失败，设置默认值
        Object.assign(userInfo, {
          name: '用户',
          username: localStorage.getItem('userId') || 'unknown',
          account: localStorage.getItem('userId') || 'unknown'
        })
      }
    } else {
      console.warn('⚠️ 缺少userId或token，无法获取用户信息')
      // 设置默认值
      Object.assign(userInfo, {
        name: '用户',
        username: 'unknown',
        account: 'unknown'
      })
    }
  } catch (error) {
    console.error('❌ 获取用户信息失败:', error)
    // 设置默认值
    Object.assign(userInfo, {
      name: '用户',
      username: 'unknown',
      account: 'unknown'
    })
  }
}

onMounted(async () => {
  await loadUserInfo()
  
  // 监听storage事件，当用户信息更新时重新加载
  window.addEventListener('storage', loadUserInfo)
})

const startLearning = () => {
  router.push('/study')
}

const goToProfile = () => {
  router.push('/profile')
}

// 获取用户姓名首字母
const getUserInitial = () => {
  if (userInfo.nickname && userInfo.nickname.length > 0) {
    return userInfo.nickname.charAt(0)
  }
  if (userInfo.name && userInfo.name.length > 0) {
    return userInfo.name.charAt(0)
  }
  if (userInfo.realName && userInfo.realName.length > 0) {
    return userInfo.realName.charAt(0)
  }
  return '用'
}
</script>

<style scoped>
.router-link-active {
  color: #2563eb;
  font-weight: 600;
}
</style>